package com.design.config;


import com.design.model.BaseResult;
import com.design.model.menus.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 统一异常处理
 *
 * @author zhuzixin
 * @date 2021-12-09 17:07
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({CommonException.class})
    @ResponseBody
    public BaseResult resolveException(CommonException e) {
        log.error("公共错误:", e);
        BaseResult result = new BaseResult();
        result.setCode(e.getCode());
        result.setDesc(e.getMessage());
        return result;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public BaseResult resolveException(MethodArgumentNotValidException e) {
        log.error("参数校验错误:", e);
        BaseResult<Void> baseResult = new BaseResult<>();
        baseResult.setCode(ErrorCode.ARGUMENT_NOT_VALID_ERROR.getCode());
        baseResult.setDesc(e.getMessage().substring(e.getMessage().lastIndexOf("["), e.getMessage().lastIndexOf("]")));
        return baseResult;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public BaseResult resolveException(Exception e) {
        log.error("系统错误:", e);
        BaseResult<Void> baseResult = new BaseResult<>();
        baseResult.setCode(ErrorCode.NU_KNOW_ERROR.getCode());
        baseResult.setDesc(ErrorCode.NU_KNOW_ERROR.getMessage());
        return baseResult;
    }

}
